Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Equivalent of R's `a %in% b`

    What is the equivalent of R's `a %in% b` where `a` and `b` are vectors in Mata?

    Just to be sure, for each element of a, I want to check if it is in b.

  • #2
    This or something similar to it came up on Statalist years ago. As I recall there is nothing that ships with Stata for this.

    You can search for that thread for a cleverer solution, but for now you can try something like the following.
    Code:
    clear *
    
    version 19
    
    mata:
    mata set matastrict on
    
    real rowvector function ainb(transmorphic vector A, transmorphic vector B) {
    
        real scalar s, i
        s = length(A)
    
        real rowvector Result
        Result = J(1, s, 0)
    
        for (i=1; i<=s; i++) Result[i] = anyof(B, A[i])
    
        return(Result)
    }
    
    // A couple of use cases:
    
    A = 1, 2, 3, 4
    B = 3, 4, 5, 6
    
    ainb(A, B)
    
    A = "A", "B", "C"
    B = "d", "e", "f"
    
    ainb(A, B)
    
    end
    
    exit
    For production code, you would want to add some input validation and so on.

    Comment


    • #3
      I misread the problem statement; I have no better answer, sorry.
      Last edited by daniel klein; 19 May 2025, 01:40.

      Comment


      • #4
        This does it for me—thanks Joseph!

        Comment

        Working...
        X